//https://leetcode.cn/problems/the-latest-time-to-catch-a-bus/description/?envType=daily-question&envId=2024-09-18https://leetcode.cn/problems/the-latest-time-to-catch-a-bus/description/?envType=daily-question&envId=2024-09-18

class Solution {
public:
    int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity) {
        int n = buses.size(), m = passengers.size();
        sort(buses.begin(), buses.end());
        sort(passengers.begin(), passengers.end());
        int sum = 0, index = 0;
        unordered_map<int, int> ma;
        for(int i = 0; i < n; i++)
        {
            sum = 0;
            while(sum < capacity && index < m && passengers[index] <= buses[i])
            {
                sum++;
                ma[passengers[index]]++;
                index++;
            }
        }
        int ans = 0;
        if(sum < capacity) ans = buses[n - 1];
        else ans = passengers[index - 1] - 1;
        while(ma[ans] > 0) ans--;
        return ans;
    }
};